#include "XVideoThread.h"
#include "XDecode.h"
#include <QDebug>
bool XVideoThread::Open(AVCodecParameters * para, IVideoCall * call, int width, int height)
{
	if (!para) {
		qDebug() << "XaudioThread::Open para is NULL";
		return false;
	}

	synpts = 0;
	videomux.lock();
	//初始化显示窗口
	this->call = call;
	if (call) {
		call->Init(width, height);
	}

	//打开解码器
	if (!decode) {
		qDebug() << "create decode";
		decode = new XDecode();
	}
	int re = true;
	if (!(decode->Open(para))) {
		qDebug() << "audio XDecode open failed";
		re = false;
	}
	else {
		qDebug() << "audio XDecode open success";
	}

	videomux.unlock();
	qDebug() << "XAudioThred::Open value = " << re;
	return re;
}

void XVideoThread::Push(AVPacket * pkt)
{
	if (!pkt) {
		qDebug() << "XAudioThread::Push pkt is NULL";
		return;
	}
	//进行阻塞
	while (!isExit) {
		videomux.lock();
		if (packs.size() < maxList) {
			packs.push_back(pkt);
			videomux.unlock();
			break;
		}
		videomux.unlock();
		msleep(1);
	}
}

void XVideoThread::run()
{

	while (!isExit) {
		videomux.lock();
		//没有数据
		if (packs.empty() || !decode) {
			videomux.unlock();
			msleep(1);
			continue;
		}
		//音视频同步，视频解码比外部传进的时间快，就等待
		if (synpts < decode->pts) {
			videomux.unlock();
			msleep(1);
			continue;
		}

		AVPacket *pkt = packs.front();
		packs.pop_front();

		bool re = decode->Send(pkt);

		if (!re) {
			qDebug() << "decode send fail.";
			videomux.unlock();
			msleep(1);
			continue;
		}
		//一次send多次 recv
		while (!isExit) {
			AVFrame *frame = decode->Recv();
			if (!frame) {
				break;
			}
			if (call) {
				call->Repaint(frame);
			}
			//显示视频
		}
		videomux.unlock();
	}
}

XVideoThread::XVideoThread()
{
}

XVideoThread::~XVideoThread()
{
}
